package org.jeecgframework.web.controller;

import com.mybatis.ext.WiseCoreService;

import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.*;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.service.CbsServiceErrorLogServiceI;
import org.jeecgframework.web.system.pojo.base.CbsServiceErrorLogEntity;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.*;


/**
 * @author onlineGenerator
 * @version V1.0
 * @Title: Controller
 * @Description: 服务单异常记录表
 * @date 2018-01-03 13:27:14
 */
@Scope("prototype")
@Controller
@RequestMapping("/cbsServiceErrorLogController")
public class CbsServiceErrorLogController extends BaseController {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(CbsServiceErrorLogController.class);

    @Autowired
    private CbsServiceErrorLogServiceI cbsServiceErrorLogService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private WiseCoreService wiseCoreService;

    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }


    /**
     * 服务单异常记录表列表 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "cbsServiceErrorLog")
    public ModelAndView cbsServiceErrorLog(HttpServletRequest request) {
        return new ModelAndView("com/zybk/cbsserviceerrorlog/cbsServiceErrorLogList");
    }

    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     * @param user
     */

    @RequestMapping(params = "datagrid")
    public void datagrid(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        try {
            Map param = new HashMap<>();
            boolean flag = false; //页面查询条件为空时不做查询
    		Map<String, String[]> parameterMap = request.getParameterMap();
            for (String key : parameterMap.keySet()) {
                if (key.equals("code") || key.equals("isClose") || key.equals("needSystemRevise") ||
                		key.equals("sn") || key.equals("createDate_begin") || key.equals("createDate_end")) {
                    if (!StringUtil.isEmpty(parameterMap.get(key)[0])) {
                        flag = true;//页面 查询条件为空不做查询
                        break;
                    }
                }
            }
            if (flag) {
	            for (Object key : request.getParameterMap().keySet()) {
	                if ((String[]) request.getParameterMap().get(key) != null) {
	                    for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
	                        if (((String[]) request.getParameterMap().get(key))[i] != null) {
	                            param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
	                        }
	                    }
	                }
	            }
	
	            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("createDate_begin")))) {
	                param.put("createDate_begin", oConvertUtils.getString(param.get("createDate_begin")) + " 00:00:00");
	            }
	            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("createDate_end")))) {
	                param.put("createDate_end", oConvertUtils.getString(param.get("createDate_end")) + " 23:59:59");
	            }
            } else {
            	param.put("isClose", 1);
            }
            wiseCoreService.selectDataGrid("getServiceErrorLogList", param, dataGrid);

        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }


        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 服务单异常记录表新增页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goAdd")
    public ModelAndView goAdd(CbsServiceErrorLogEntity cbsServiceErrorLog, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(cbsServiceErrorLog.getId())) {
            cbsServiceErrorLog = cbsServiceErrorLogService.getEntity(CbsServiceErrorLogEntity.class, cbsServiceErrorLog.getId());
            req.setAttribute("cbsServiceErrorLogPage", cbsServiceErrorLog);
        }
        return new ModelAndView("com/zybk/cbsserviceerrorlog/cbsServiceErrorLog-add");
    }


    /**
     * 添加服务单异常记录表
     *
     * @param ids
     * @return
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(CbsServiceErrorLogEntity cbsServiceErrorLog, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "服务单异常记录表添加成功";
        try {
            cbsServiceErrorLogService.save(cbsServiceErrorLog);
            systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "服务单异常记录表添加失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 服务单异常记录表编辑页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView goUpdate(HttpServletRequest req) {
        if (StringUtil.isNotEmpty(req.getParameter("id"))) {
            CbsServiceErrorLogEntity cbsServiceErrorLog = cbsServiceErrorLogService.getEntity(CbsServiceErrorLogEntity.class, req.getParameter("id"));
            req.setAttribute("cbsServiceErrorLogPage", cbsServiceErrorLog);
        }

        boolean flag = false;
        TSUser user = ResourceUtil.getSessionUserName();
        List<Map<String, Object>> roleList = systemService.findForJdbc("SELECT * FROM t_s_role r LEFT JOIN t_s_role_user u ON r.id = u.roleid where u.userid = '" + user.getId() + "';");
        if (StringUtil.isNotEmpty(roleList)) {
            if (roleList.size() > 0) {
                String num = (String) roleList.get(0).get("rolecode");
                if (num.equals(StaticValue.ROLE_CODE_ADMIN)) {
                    flag = true;
                }
            }
        }

        if (flag) {
            return new ModelAndView("com/zybk/cbsserviceerrorlog/cbsServiceErrorLog-adminUpdate");
        } else {
            return new ModelAndView("com/zybk/cbsserviceerrorlog/cbsServiceErrorLog-update");
        }
    }

    /**
     * 更新服务单异常记录表
     *
     * @param ids
     * @return
     */
    @RequestMapping(params = "doUpdate")
    @ResponseBody
    public AjaxJson doUpdate(CbsServiceErrorLogEntity cbsServiceErrorLog, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "服务单异常记录更新成功";
        String id = cbsServiceErrorLog.getId();
        if (StringUtil.isNotEmpty(id)) {
            String description = cbsServiceErrorLog.getDescription();
            String abnormalResult = cbsServiceErrorLog.getAbnormalResult();
            TSUser user = ResourceUtil.getSessionUserName();
            CbsServiceErrorLogEntity t = cbsServiceErrorLogService.get(CbsServiceErrorLogEntity.class, cbsServiceErrorLog.getId());
            try {
                //判断角色是否是管理员
                boolean flag = false;
                List<Map<String, Object>> roleList = systemService.findForJdbc("SELECT * FROM t_s_role r LEFT JOIN t_s_role_user u ON r.id = u.roleid where u.userid = '" + user.getId() + "';");
                if (StringUtil.isNotEmpty(roleList)) {
                    if (roleList.size() > 0) {
                        String num = (String) roleList.get(0).get("rolecode");
                        if (num.equals(StaticValue.ROLE_CODE_ADMIN)) {
                            flag = true;  //是管理员
                        }
                    }
                }

                if (flag) {
                    t.setAdminAbnormalResult(cbsServiceErrorLog.getAdminAbnormalResult());
                    t.setAdminDescription(cbsServiceErrorLog.getAdminDescription());
                    t.setAdminUpdateDate(new Date());
                    t.setAdminUpdateBy("管理员");
                    t.setNeedSystemRevise(cbsServiceErrorLog.getNeedSystemRevise());
                } else {
                    t.setDescription(description);
                    t.setAbnormalResult(abnormalResult);
                    t.setUpdateDate(new Date());
                    t.setUpdateName(user.getUserName());
                    t.setUpdateBy(user.getRealName());
                    t.setNeedSystemRevise(cbsServiceErrorLog.getNeedSystemRevise());
                }
                t.setIsClose(StaticValue.service_ERROR_Log_Type_2);
                cbsServiceErrorLogService.saveOrUpdate(t);
                if (flag) {
                    systemService.updateBySqlString("update CBS_SERVICE_ERROR_LOG set update_name='" + "" + "',update_date=null where id = '" + cbsServiceErrorLog.getId() + "'");
                }
                systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
            } catch (Exception e) {
                e.printStackTrace();
                message = "服务单异常记录更新失败";
                throw new BusinessException(e.getMessage());
            }
            j.setMsg(message);
        }

        return j;
    }


    /**
     * 删除服务单异常记录表
     *
     * @return
     */
    @RequestMapping(params = "doDel")
    @ResponseBody
    public AjaxJson doDel(CbsServiceErrorLogEntity cbsServiceErrorLog, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        cbsServiceErrorLog = systemService.getEntity(CbsServiceErrorLogEntity.class, cbsServiceErrorLog.getId());
        message = "服务单异常记录表删除成功";
        try {
            cbsServiceErrorLogService.delete(cbsServiceErrorLog);
            systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "服务单异常记录表删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 批量删除服务单异常记录表
     *
     * @return
     */
    @RequestMapping(params = "doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "服务单异常记录表删除成功";
        try {
            for (String id : ids.split(",")) {
                CbsServiceErrorLogEntity cbsServiceErrorLog = systemService.getEntity(CbsServiceErrorLogEntity.class, id);
                cbsServiceErrorLogService.delete(cbsServiceErrorLog);
                systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
            }
        } catch (Exception e) {
            e.printStackTrace();
            message = "服务单异常记录表删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXls")
    public void exportXls(HttpServletRequest request, HttpServletResponse response) {
        cbsServiceErrorLogService.exportXLS(request, response);
    }

    /**
     * 导出excel 使模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXlsByT")
    public String exportXlsByT(CbsServiceErrorLogEntity cbsServiceErrorLog, HttpServletRequest request, HttpServletResponse response
            , DataGrid dataGrid, ModelMap modelMap) {
        modelMap.put(TemplateExcelConstants.FILE_NAME, "服务单异常记录表");
        modelMap.put(TemplateExcelConstants.PARAMS, new TemplateExportParams("Excel模板地址"));
        modelMap.put(TemplateExcelConstants.MAP_DATA, null);
        modelMap.put(TemplateExcelConstants.CLASS, CbsServiceErrorLogEntity.class);
        modelMap.put(TemplateExcelConstants.LIST_DATA, null);
        return TemplateExcelConstants.JEECG_TEMPLATE_EXCEL_VIEW;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(params = "importExcel", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<CbsServiceErrorLogEntity> listCbsServiceErrorLogEntitys = ExcelImportUtil.importExcelByIs(file.getInputStream(), CbsServiceErrorLogEntity.class, params);
                for (CbsServiceErrorLogEntity cbsServiceErrorLog : listCbsServiceErrorLogEntitys) {
                    cbsServiceErrorLogService.save(cbsServiceErrorLog);
                }
                j.setMsg("文件导入成功！");
            } catch (Exception e) {
                j.setMsg("文件导入失败！");
                logger.error(ExceptionUtil.getExceptionMessage(e));
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return j;
    }
}
